import React, { useEffect, useMemo, useState } from 'react';
import { Card, Space, Tabs, Table, Select, Button, message, Tree, Form, Modal } from 'antd';

// 本地存储键名
const LS_USER_ROLE = 'authority-user-role-map';
const LS_ROLE_AUTH = 'authority-role-auth-map';

const ROLE_LIST = [
  { id: 1, name: '系统管理员' },
  { id: 2, name: '运营管理员' },
  { id: 3, name: '访客' },
];

const USER_LIST = Array.from({ length: 15 }).map((_, i) => ({
  id: i + 1,
  userName: `user_${i + 1}`,
  nickName: `昵称_${i + 1}`,
}));

// 示例权限树（可根据实际菜单做扩展）
const PERM_TREE = [
  {
    title: '系统管理', key: 'system', children: [
      { title: '用户管理', key: 'system:user' },
      { title: '字典数据', key: 'system:dictionary-data' },
      { title: '邮箱配置', key: 'system:email' },
    ],
  },
  {
    title: '权限管理', key: 'authority', children: [
      { title: '角色管理', key: 'authority:role' },
      { title: '菜单管理', key: 'authority:menu' },
      { title: '授权管理', key: 'authority:authorization' },
      { title: '登录日志', key: 'authority:login' },
      { title: '操作日志', key: 'authority:operation' },
      { title: '隐私协议日志', key: 'authority:privacy' },
    ],
  },
];

function loadUserRole() {
  try {
    const raw = localStorage.getItem(LS_USER_ROLE);
    return raw ? JSON.parse(raw) : {};
  } catch (e) {
    return {};
  }
}

function saveUserRole(map) {
  localStorage.setItem(LS_USER_ROLE, JSON.stringify(map));
}

function loadRoleAuth() {
  try {
    const raw = localStorage.getItem(LS_ROLE_AUTH);
    return raw ? JSON.parse(raw) : {};
  } catch (e) {
    return {};
  }
}

function saveRoleAuth(map) {
  localStorage.setItem(LS_ROLE_AUTH, JSON.stringify(map));
}

export default function Authorization() {
  const [activeKey, setActiveKey] = useState('userRole');

  // 用户角色映射
  const [userRoleMap, setUserRoleMap] = useState(() => loadUserRole());
  const userRoleColumns = [
    { title: '用户名', dataIndex: 'userName', key: 'userName', width: 220 },
    { title: '昵称', dataIndex: 'nickName', key: 'nickName', width: 220 },
    {
      title: '角色', key: 'role', render: (_, row) => (
        <Select
          style={{ width: 200 }}
          value={userRoleMap[row.id] ?? undefined}
          placeholder="请选择角色"
          allowClear
          options={ROLE_LIST.map((r) => ({ label: r.name, value: r.id }))}
          onChange={(val) => {
            setUserRoleMap((m) => ({ ...m, [row.id]: val }));
          }}
        />
      )
    },
  ];

  const onSaveUserRole = () => {
    saveUserRole(userRoleMap);
    message.success('用户角色已保存');
  };

  // 角色授权
  const [roleId, setRoleId] = useState(ROLE_LIST[0].id);
  const [roleAuthMap, setRoleAuthMap] = useState(() => loadRoleAuth());
  const checkedKeys = useMemo(() => roleAuthMap[roleId] ?? [], [roleId, roleAuthMap]);

  const onCheckAuth = (keys) => {
    setRoleAuthMap((m) => ({ ...m, [roleId]: keys }));
  };

  const onSaveRoleAuth = () => {
    saveRoleAuth(roleAuthMap);
    message.success('角色权限已保存');
  };

  return (
    <Card title="授权管理">
      <Tabs
        activeKey={activeKey}
        onChange={setActiveKey}
        items={[
          {
            key: 'userRole',
            label: '用户角色',
            children: (
              <Space direction="vertical" style={{ width: '100%' }} size="middle">
                <Table
                  rowKey="id"
                  columns={userRoleColumns}
                  dataSource={USER_LIST}
                  pagination={{ pageSize: 10 }}
                />
                <Button type="primary" onClick={onSaveUserRole}>保存</Button>
              </Space>
            ),
          },
          {
            key: 'userAuth',
            label: '角色授权',
            children: (
              <Space direction="vertical" style={{ width: '100%' }} size="middle">
                <Space>
                  <span>选择角色：</span>
                  <Select
                    style={{ width: 240 }}
                    value={roleId}
                    options={ROLE_LIST.map((r) => ({ label: r.name, value: r.id }))}
                    onChange={setRoleId}
                  />
                  <Button type="primary" onClick={onSaveRoleAuth}>保存</Button>
                </Space>
                <Tree
                  checkable
                  defaultExpandAll
                  checkedKeys={checkedKeys}
                  onCheck={(keys) => onCheckAuth(keys)}
                  treeData={PERM_TREE}
                />
              </Space>
            ),
          },
        ]}
      />
    </Card>
  );
}